package com.noah.note.manager;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.noah.note.R;
import com.noah.note.ui.HomeActivity;
import com.noah.note.utils.PermissionUtil;

/**
 * Created by zzh on 2018/8/17.
 */

public class ForegroundServiceManager extends Service {

    public static final int PID = 121;
    private static ForegroundServiceManager instance;
    private Context context;
    private ServiceConnection conn;
    private NotificationManager notificationManager;
    private boolean isInit = false;
    private ServiceListener serviceListener;
    private MyBinder myBinder = new MyBinder();

    public static ForegroundServiceManager getInstance() {
        if (instance == null) {
            synchronized (ForegroundServiceManager.class) {
                if (instance == null) {
                    instance = new ForegroundServiceManager();
                }
            }
        }
        return instance;
    }

    public void init(Context context){
        this.context = context;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public class MyBinder extends Binder {
        public ForegroundServiceManager getService() {
            return ForegroundServiceManager.this;
        }
    }

    public void startService(Context context, ServiceListener serviceListener) {
        this.serviceListener = serviceListener;
        conn = new MyConnection();
        context.bindService(new Intent(context, ForegroundServiceManager.class), conn, context.BIND_AUTO_CREATE);//绑定存在自动创建
    }

    public void stopService(Context context) {
        context.unbindService(conn);
    }

    public void openForeground(ForegroundListener listener) {
        if (isInit) {
            if (PermissionUtil.isNotificationEnabled(context)) {
                myBinder.getService().startForeground(PID, getNotification());
            } else {
                listener.onFailed();
            }
        }
    }

    public void open(final Context context) {
        openForeground(new ForegroundServiceManager.ForegroundListener() {

            @Override
            public void onFailed() {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("请打开通知栏权限");
                builder.setPositiveButton("前去开启", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        PermissionUtil.goNotificationSetting(context);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }

    public Notification getNotification() {
        Intent nfIntent = new Intent(context, HomeActivity.class);
        PendingIntent contentIntent = PendingIntent.getBroadcast(context.getApplicationContext(), PID, nfIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification;
        if (Build.VERSION.SDK_INT < 16) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext());
            notification = builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentTitle(context.getResources().getString(R.string.app_name))
                    .setContentIntent(contentIntent)
                    .build();// getNotification()
        } else {//>=16版本
            Notification.Builder builder;
            if (Build.VERSION.SDK_INT >= 26) {
                //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
                if (null == notificationManager) {
                    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                }
                NotificationChannel notificationChannel = new NotificationChannel(context.getPackageName(),
                        "BackgroundLocation", NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new Notification.Builder(context.getApplicationContext(), context.getPackageName());
            } else {
                builder = new Notification.Builder(context.getApplicationContext());
            }
            notification = builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentTitle(context.getResources().getString(R.string.app_name))
                    .setContentIntent(contentIntent)
                    .build();// getNotification()
        }
        return notification;
    }

    public class MyConnection implements ServiceConnection {

        @Override//当服务与Activity 连接时建立
        public void onServiceConnected(ComponentName name, IBinder binder) {
            //只有当service onbind方法返回值不为null 调用
            Log.e("TAG", "onServiceConnected");
            myBinder = (MyBinder) binder;
            isInit = true;
            serviceListener.onSuccess();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("TAG", "onServiceDisconnected");
        }
    }

    public interface ForegroundListener {
        void onFailed();
    }

    public interface ServiceListener {
        void onSuccess();
    }
}
